package com.tjc.media.service.impl;

import java.util.*;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.config.TencentCosConfig;
import com.tjc.media.domain.Attachment;
import com.tjc.media.enums.BizType;
import com.tjc.media.mapper.AttachmentMapper;
import com.tjc.media.service.TencentCosService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tjc.media.mapper.SongInfoMapper;
import com.tjc.media.domain.SongInfo;
import com.tjc.media.service.ISongInfoService;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 歌曲信息Service业务层处理
 * 
 * @author 大根教会
 * @date 2025-09-23
 */
@Service
public class SongInfoServiceImpl implements ISongInfoService 
{
    @Autowired
    private SongInfoMapper songInfoMapper;

    @Autowired
    private AttachmentMapper attachmentMapper;

    @Autowired
    private TencentCosService tencentCosService;

    @Resource
    private TencentCosConfig tencentCosConfig;

    /**
     * 查询歌曲信息
     * 
     * @param songId 歌曲信息主键
     * @return 歌曲信息
     */
    @Override
    public SongInfo selectSongInfoBySongId(Long songId)
    {
        SongInfo songInfo = songInfoMapper.selectSongInfoBySongId(songId);
        if(songInfo == null) {
            return null;
        }
        List<Long> songIdList = new ArrayList<>();
        songIdList.add(songId);
        List<Attachment> attachmentList = selectAttachmentList(songIdList, this.getBizTypes());
        for (Attachment attachment : attachmentList) {
            BizType bizType = BizType.getByCode(attachment.getBizType());
            switch (Objects.requireNonNull(bizType)) {
                case SONG:
                    String songFileUrl = attachment.getFileUrl();
                    songInfo.setSongOriginalName(attachment.getFileName());
                    songInfo.setSongDisplayName(attachment.getFileName());
                    songInfo.setSongStorageName(songFileUrl.substring(songFileUrl.lastIndexOf("/")+1));
                    songInfo.setSongFileUrl(songFileUrl);
                    songInfo.setSongFileSize(attachment.getFileSize());
                    break;
                case COVER:
                    String coverFileUrl = attachment.getFileUrl();
                    songInfo.setCoverOriginalName(attachment.getFileName());
                    songInfo.setCoverDisplayName(attachment.getFileName());
                    songInfo.setCoverStorageName(coverFileUrl.substring(coverFileUrl.lastIndexOf("/")+1));
                    songInfo.setCoverFileUrl(attachment.getFileUrl());
                    songInfo.setCoverFileSize(attachment.getFileSize());
                    break;
                case LYRIC:
                    String lyricFileUrl = attachment.getFileUrl();
                    songInfo.setLyricOriginalName(attachment.getFileName());
                    songInfo.setLyricDisplayName(attachment.getFileName());
                    songInfo.setLyricStorageName(lyricFileUrl.substring(lyricFileUrl.lastIndexOf("/")+1));
                    songInfo.setLyricFileUrl(lyricFileUrl);
                    songInfo.setLyricFileSize(attachment.getFileSize());
                    break;
                default:
                    throw new ServiceException("附件业务类型未找到该值："+attachment.getBizType());
            }
        }
        return songInfo;
    }

    /**
     * 查询歌曲信息列表
     * 
     * @param songInfo 歌曲信息
     * @return 歌曲信息
     */
    @Override
    public List<SongInfo> selectSongInfoList(SongInfo songInfo)
    {
        return songInfoMapper.selectSongInfoList(songInfo);
    }

    /**
     * 新增歌曲信息
     * 
     * @param request 歌曲信息
     * @return 结果
     */
    @Override
    public int insertSongInfo(SongInfo request)
    {
        Long userId = SecurityUtils.getUserId();
        request.setCreateUserid(userId);
        request.setCreateTime(DateUtils.getNowDate());
        request.setUpdateUserid(userId);
        int result = songInfoMapper.insertSongInfo(request);
        //上传文件到COS
        uploadFile(request, request, true);
        return result;
    }

    /**
     * 修改歌曲信息
     * 
     * @param request 歌曲信息
     * @return 结果
     */
    @Override
    public int updateSongInfo(SongInfo request)
    {
        Long userId = SecurityUtils.getUserId();
        request.setUpdateUserid(userId);
        request.setUpdateTime(DateUtils.getNowDate());
        //上传文件到COS
        uploadFile(request, request, false);
        return songInfoMapper.updateSongInfo(request);
    }

    /**
     * 批量删除歌曲信息
     * 
     * @param songIds 需要删除的歌曲信息主键
     * @return 结果
     */
    @Override
    public int deleteSongInfoBySongIds(Long[] songIds)
    {
        //删除文件
        List<Long> songIdList = Arrays.asList(songIds);
        this.deleteFile(songIdList, null);
        return songInfoMapper.deleteSongInfoBySongIds(songIds);
    }

    /**
     * 删除歌曲信息信息
     * 
     * @param songId 歌曲信息主键
     * @return 结果
     */
    @Override
    public int deleteSongInfoBySongId(Long songId)
    {
        //删除文件
        List<Long> songIdList = new ArrayList<>();
        songIdList.add(songId);
        this.deleteFile(songIdList, null);
        return songInfoMapper.deleteSongInfoBySongId(songId);
    }

    /**
     * 上传文件到COS
     * @param request
     * @param songInfo
     * @param isAdd
     */
    private void uploadFile(SongInfo request, SongInfo songInfo, boolean isAdd) {
        uploadFile(request.getSongFile(), tencentCosConfig.getAudioDir() + request.getSongStorageName(), BizType.SONG.getCode(), songInfo.getSongId(), isAdd);
        uploadFile(request.getCoverFile(), tencentCosConfig.getCoverDir() + request.getCoverStorageName(), BizType.COVER.getCode(), songInfo.getSongId(), isAdd);
        uploadFile(request.getLyricFile(), tencentCosConfig.getLyricDir() + request.getLyricStorageName(), BizType.LYRIC.getCode(), songInfo.getSongId(), isAdd);
    }

    /**
     * 上传文件到COS
     * @param file
     * @param key
     * @param bizType
     * @param bizId
     * @param isAdd
     */
    private void uploadFile(MultipartFile file, String key, Integer bizType, Long bizId, boolean isAdd) {
        if (file == null) {
            return;
        }
        //检测文件路径是否存在
        boolean isCheck = bizType == BizType.SONG.getCode() || bizType == BizType.LYRIC.getCode();
        Long exceptBizId = null;
        if(isCheck && isAdd && tencentCosService.doesObjectExist(tencentCosConfig.getBucketName(), key)) {
            throw new ServiceException("COS上已存在该文件："+key);
        } else if (isCheck) {
            exceptBizId = bizId;
        }
        if (attachmentMapper.selectCountByFileKey(key, tencentCosConfig.getBucketName(), exceptBizId) > 0) {
            throw new ServiceException("数据库中已存在该文件："+key);
        }
        if(!isAdd) {
            //删除旧的文件
            List<Long> songIdList = Collections.singletonList(bizId);
            this.deleteFile(songIdList, Collections.singletonList(bizType));
        }
        String uploadResult = tencentCosService.uploadFile(file, key);
        String fileName = file.getOriginalFilename();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Attachment attachment = new Attachment();
        attachment.setFileName(fileName);
        attachment.setFileKey(key);
        attachment.setFileUrl(uploadResult);
        attachment.setFileSize(file.getSize());
        attachment.setFileExtension(Objects.requireNonNull(fileName).substring(fileName.lastIndexOf(".")));
        attachment.setMimeType(file.getContentType());
        attachment.setBucketName(tencentCosConfig.getBucketName());
        attachment.setBizType(bizType);
        attachment.setBizId(bizId);
        attachment.setUploadUserid(loginUser.getUserId());
        attachment.setUploadTime(DateUtils.getNowDate());
        if(!isAdd) {
            attachmentMapper.deleteBizId(bizType, bizId);
        }
        attachmentMapper.insertAttachment(attachment);
    }

    private List<Integer> getBizTypes() {
        List<Integer> bizTypes = new ArrayList<>();
        bizTypes.add(BizType.SONG.getCode());
        bizTypes.add(BizType.COVER.getCode());
        bizTypes.add(BizType.LYRIC.getCode());
        return bizTypes;
    }

    /**
     * 查询附件列表
     * @param songIds
     * @return
     */
    private List<Attachment> selectAttachmentList(List<Long> songIds, List<Integer> bizTypes) {
        Attachment attachment = new Attachment();
        attachment.setBizTypes(bizTypes);
        attachment.setBizIds(songIds);
        return attachmentMapper.selectAttachmentList(attachment);
    }

    /**
     * 删除文件
     * @param songIds
     */
    private void deleteFile(List<Long> songIds, List<Integer> bizTypes) {
        bizTypes = bizTypes == null ? this.getBizTypes() : bizTypes;
        List<Attachment> attachmentList = selectAttachmentList(songIds, bizTypes);
        if(attachmentList.isEmpty()) {
            return;
        }
        //删除cos文件
        for (Attachment attach : attachmentList) {
            tencentCosService.deleteFile(attach.getFileKey());
        }
        //删除数据库记录
        attachmentMapper.deleteBizIds(bizTypes, songIds);
    }
}
